﻿using Microsoft.Office.Interop.Excel;
using mshtml;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WPFWebControl
{
    public enum StepProcess
    {
        GOTO_LINK = 0,
        REMOVE_JS,
        REMOVE_DIALOG
    };

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : System.Windows.Window, INotifyPropertyChanged
    {       
     
        Entities db = null;
        BackgroundWorker mainThread = null;
        private bool m_bCLik = false;
        private bool m_bNew = true;
        tblLinkBuck activeItem = null;
        private bool m_bNewUrl = false;
        private bool m_bRedirect = false;

        StepProcess mainProcess;

        public MainWindow()
        {           
            InitializeComponent();
            _listLinks = new ObservableCollection<tblLinkBuck>();
            DataContext = this;
           WinInetInterop.RestoreSystemProxy();
           mainProcess = StepProcess.GOTO_LINK;
           //WinInetInterop.SetConnectionProxy("178.254.161.68:6666");
           HideScriptErrors(MyWebBrowser, true);

            try
            {
                db = new Entities();               
            }
            catch (System.Exception ex)
            {
                if (MessageBox.Show("Do you want reconnect?", "Connect database", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                {
                    db = new Entities();
                }
                else
                {
                    Close();
                }
            }           
           
        }

        ObservableCollection<tblLinkBuck> _listLinks;
        public ObservableCollection<tblLinkBuck> ListLinks
        {
            get
            {
                return _listLinks;
            }
            set
            {
                if (_listLinks != value)
                {
                    _listLinks = value;
                    OnPropertyChanged("ListLinks");
                }
            }

        }

        private void assignProcess(DoWorkEventHandler run, RunWorkerCompletedEventHandler completed)
        {
            mainThread = new BackgroundWorker();
            mainThread.DoWork += run;
            mainThread.RunWorkerCompleted += completed;
            mainThread.WorkerReportsProgress = true;
            mainThread.WorkerSupportsCancellation = true;
            
            mainThread.RunWorkerAsync();
        }

        private void StartWaitToClickThread()
        {                   
            assignProcess(delay7second, taskCompleted);
        }

        

        private void StartWaitToNextThread()
        {            
            assignProcess(runNextItem, tasknextItem);

        }
      
        private void delay7second(Object sender, DoWorkEventArgs e)
        {
            Thread.Sleep(7000);
        }

        private void delay1second(Object sender, DoWorkEventArgs e)
        {
            Thread.Sleep(1000);

        }


        private void doWorkFLV(Object sender, RunWorkerCompletedEventArgs e)
        {
            //"Windows Internet Explorer"
            IntPtr zero = IntPtr.Zero;
            zero = FindWindow(null, "WebBrowser");
            if (zero != IntPtr.Zero)
            {
                ShowWindow(zero, 6);
                System.Collections.Generic.List<IntPtr> listHwnd = GetAllChildrenWindowHandles(zero, 100);
                foreach (IntPtr item in listHwnd)
                {
                    System.Collections.Generic.List<IntPtr> listSubHwnd = GetAllChildrenWindowHandles(item, 100);
                    foreach (IntPtr Subitem in listSubHwnd)
                    {
                        System.Collections.Generic.List<IntPtr> listSubSubHwnd = GetAllChildrenWindowHandles(Subitem, 100);
                        foreach (IntPtr SubSubitem in listSubSubHwnd)
                        {
                            string str = GetWindowCaption(SubSubitem);
                            if (str == "&Leave this page")
                            {
                                PostMessage(SubSubitem, 0x0100, 0x0D, 1);
                                m_start_enter = true;
                            }
                        }
                    }
                }
            }
        }
        private void runNextItem(Object sender, DoWorkEventArgs e)
        {
            while (true)
            {
                Thread.Sleep(2000);
                if (m_bEnter)
                {                  
                    break;
                }

            }

        }

        

        private void startRemoveFLVDialog()
        {
            assignProcess(delay1second, doWorkFLV);
        }

        private void tasknextItem(Object sender, RunWorkerCompletedEventArgs e)
        {
            //mainThread.CancelAsync();
            gotoNextItem();
        }

        private bool m_bEnter = false;

        private void startSenKey(Object sender, RunWorkerCompletedEventArgs e)
        {
            //mainThread.CancelAsync();

            if (!mainThread.IsBusy)
            {               
                StartWaitToNextThread();
                tbLog.Text += "->Enter";
                                
                m_bEnter = true;
            }
            
        }

      
        private void taskCompleted(Object sender, RunWorkerCompletedEventArgs e)
        {
            if (!mainThread.IsBusy)
            {
                //mainThread.CancelAsync();
                
                var doc = (mshtml.HTMLDocument)MyWebBrowser.Document;

                mshtml.HTMLSpanElement spanItem = (mshtml.HTMLSpanElement)doc.getElementById("skip_disabled");

                if (spanItem != null && spanItem.style != null && spanItem.style.cssText != null && spanItem.style.cssText.Contains("DISPLAY: none;"))
                {
                    mshtml.HTMLAnchorElement itemDiv = (mshtml.HTMLAnchorElement)doc.getElementById("skiplink");
                    if (itemDiv != null)
                    {

                        tbLog.Text += " ->clicked";                      
                        itemDiv.click();

                        //Start check some missing FLV
                        
                        m_bCLik = true;

                    }
                }
                else
                {                   
                    StartWaitToClickThread();
                }
            }
           
        }

        private void onStart(object sender, RoutedEventArgs e)
        {
            tbLog.Text = "";

            mainThread = new BackgroundWorker();           
            ListLinks = new ObservableCollection<tblLinkBuck>((from p in db.tblLinkBucks select p).ToList());
           
            if (ListLinks.Count > 0)
            {
                tblLinkBuck item = ListLinks.ElementAt(0);
                processAt(item);
                m_nCount = 1;
            }
           
        }

        private int m_nCount = 0;

        
        private void OnNaviagted(object sender, NavigationEventArgs e)
        {
           
            string sUrl = e.Uri.ToString();
             tbLog.Text += "->Navigated(" + sUrl +")";
            if (sUrl == activeItem.LinkBuck)
            {
                m_bNewUrl = false;
            }
            else if (sUrl == activeItem.LinkBuck + "#")
            {
               
            }
            else
                m_bNewUrl = true;
        }

        
        private void OnNavigating(object sender, NavigatingCancelEventArgs e)
        {
            string sUrl = e.Uri.ToString();
            tbLog.Text += "->Navigating(" + sUrl + ")";
            if (!sUrl.Contains(activeItem.LinkBuck))
            {
                //this.Activate();
                StartWaitConfirmThread();
                m_bRedirect = true;
            }
            
        }

        #region PropertyChanged
        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string propName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propName));
            }
        }

        #endregion
    }
}
